<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>事件冒泡和捕获</title>
  </head>
  <style>
    .box1 {
      width: 300px;
      height: 300px;
      background-color: orangered;
    }
    .box2 {
      width: 200px;
      height: 200px;
      background-color: yellowgreen;
    }
    .box3 {
      width: 100px;
      height: 100px;
      background-color: turquoise;
    }
  </style>
  <body>
    <div class="box1">
      <div class="box2">
        <div class="box3"></div>
      </div>
    </div>
    <p></p>

    <input type="text" id="input" />

    <p></p>

    <div id="input-wapper">
      <input type="text" />
    </div>
  </body>
</html>

<script>
  const box1 = document.querySelector(".box1");
  const box2 = document.querySelector(".box2");
  const box3 = document.querySelector(".box3");

  box1.addEventListener(
    "click",
    function () {
      console.log("%c box1", "color:red");
    },
    true
  );
  box2.addEventListener(
    "click",
    function () {
      console.log("%c box2", "color:red");
    },
    true
  );
  box3.addEventListener(
    "click",
    function () {
      console.log("%c box3", "color:red");
    },
    true
  );
  document.body.addEventListener(
    "click",
    function () {
      console.log("%c body", "color:red");
    },
    true
  );
  document.addEventListener(
    "click",
    function () {
      console.log("%c document", "color:red");
    },
    true
  );
  window.addEventListener(
    "click",
    function () {
      console.log("%c window", "color:red");
    },
    true
  );

  box1.addEventListener("click", function () {
    console.log("box1");
  });
  box2.addEventListener("click", function () {
    console.log("box2");
  });
  box3.addEventListener("click", function () {
    console.log("box3");
  });
  document.body.addEventListener("click", function () {
    console.log("body");
  });
  document.addEventListener("click", function () {
    console.log("document");
  });
  window.addEventListener("click", function () {
    console.log("window");
  });
</script>

<script>
  const input = document.querySelector("input");
  // 阻止默认事件
  input.addEventListener(
    "keypress",
    function (e) {
      if (/^\d+$/.test(+e.key) === false) e.preventDefault();
    },
    false
  );
  // 阻止事件传递
  const inputwapper = document.querySelector("#input-wapper");
  inputwapper.addEventListener(
    "keypress",
    function (e) {
      if (/^\d+$/.test(+e.key) === true) e.stopPropagation();
    },
    true
  );
  inputwapper.querySelector("input").addEventListener(
    "keypress",
    function (e) {
      console.log(e.key);
    },
    true
  );
</script>
